import * as step from '@flow-step/step-toolkit'
import * as path from 'path'
import * as fs from 'fs'

const SEP = path.sep;


// Set SSH private key for the repo we work on
export function SetSSHPrivateKey(repoDirName:string) {
    let workDir = process.env.WORK_SPACE;

    let sources = process.env.SOURCES as string;

    let sourceList = JSON.parse(sources);
    for (let i = 0; i < sourceList.length; i++) {
        let obj = sourceList[i];
        if (obj.name != repoDirName) {
            continue;
        }
        let data = obj.data;
        let hostGitPK = data.sshPrivateKey;
        if (hostGitPK == undefined) {
            break;
        }
        writePrivateKey(`${workDir}${SEP}.ssh`, hostGitPK);
        process.env.GIT_SSH_COMMAND = `ssh -i '${workDir}${SEP}.ssh${SEP}id_rsa' -o StrictHostKeyChecking=no`;
        break;
    }
}

function writePrivateKey(path: string, privateKey: string) {
    if (!fs.existsSync(path)) {
        fs.mkdirSync(path);
    }
    if (fs.existsSync(`${path}${SEP}id_rsa`)) {
        fs.chmodSync(`${path}${SEP}id_rsa`, 0o600);
    }
    fs.writeFileSync(`${path}${SEP}id_rsa`, privateKey);
    fs.chmodSync(`${path}${SEP}id_rsa`, 0o400);
    step.info('Write SSH private key success');
}